import { addressPost, addressGet, addressPut } from "./../api/user";
import { useUserStore } from "./userStore";
import { defineStore } from "pinia";

//这个类型需要同时满足list跟add组件的需求
export interface IAddressType {
  id: string;
  name: string;
  tel: string;
  address: string;
  isDefault: boolean;
  province: string;
  city: string;
  county: string;
  addressDetail: string;
  userid: string;
  objectId: string;
}
interface IAddressState {
  list: Array<IAddressType>;
  editIdx: number;
  choosenId: string;
}
export const useAddress = defineStore("address", {
  state: (): IAddressState => {
    return {
      list: [
        // {
        //   id: "1",
        //   name: "张三",
        //   tel: "13000000000",
        //   address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室",
        //   isDefault: true,
        // },
        // {
        //   id: "2",
        //   name: "李四",
        //   tel: "1310000000",
        //   address: "浙江省杭州市拱墅区莫干山路 50 号",
        // },
      ],
      editIdx: -1, //-1代表新增、其他数字代表编辑
      choosenId: "", //记录被勾选的地址id
    };
  },
  getters: {
    addressInfo(): IAddressType | undefined {
      if (this.editIdx !== -1) {
        return this.list[this.editIdx];
      }
    },
    // 根据choosenId获取被勾选的地址数据
    choosenAddress(): IAddressType | undefined {
      console.log(this.choosenId);
      return this.list.find((item) => item.id == this.choosenId);
    },
  },
  actions: {
    // 新增地址
    addressAddAct(addressObj: IAddressType) {
      let { province, city, county, addressDetail, isDefault } = addressObj;
      addressObj.address = province + city + county + addressDetail;
      // addressObj.id = Math.random() + "";
      const user = useUserStore();
      if (user.userInfo) {
        addressObj.userid = user.userInfo.objectId;
      }
      //判断新地址是否勾选了默认
      if (isDefault) {
        this.list.forEach((item) => {
          item.isDefault = false;
        });
      }
      //新增
      if (this.editIdx == -1) {
        addressPost(addressObj).then((res) => {
          addressObj.id = res.data.objectId;
          this.list.push(addressObj);
        });
      } else {
        //修改
        this.list[this.editIdx] = addressObj;
        addressPut(addressObj.objectId, addressObj);
      }
    },
    //删除
    addressDelAct() {
      this.list.splice(this.editIdx, 1);
    },
    // 根据默认地址选项、获取被勾选的地址id
    addressIdInitAct() {
      let obj = this.list.find((item) => item.isDefault);
      if (obj) {
        this.choosenId = obj.id;
      }
    },
    //从数据库获取地址
    async addressListInitAct(userid: string) {
      let res = await addressGet(userid);
      this.list = res.data.results;
    },
  },
  persist: {
    key: "vue-pinia-address",
  },
});
